package com.example.service.impl;

import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.pojo.Dept;
import com.example.pojo.DeptLog;
import com.example.service.DeptLogService;
import com.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hyk~
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    //查询
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //删除
    @Transactional(rollbackFor = Exception.class) //spring事务管理
    @Override
    public void DeleteDept(Integer id) {
        try {
            deptMapper.DeleteDept(id); //根据id删除部门数据
//            int i = 3/0; //异常，删除的部门数据会通过事务回滚恢复
            empMapper.deleteByDeptId(id); //根据被删除的部门id 删除该部门下的员工
        } finally { //无论上面代码成功或失败都会执行
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，解散的部门id是:"+id);
            deptLogService.insert(deptLog);
        }

    }

    //新增
    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now() );
        deptMapper.addDept(dept);
    }

    //根据id查询
    @Override
    public Dept selectByDeptId(Integer id) {
        return deptMapper.selectByDeptId(id);
    }

    //修改
    @Override
    public void update(Dept dept) {
        //设置修改时间为当前
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
